package zhangxinhua.lanqiaoyun.sp8;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zxhtom
 */
public class NumberAddAns {
    public static void main(String[] args) {
        NumberAddAns ans = new NumberAddAns();
        Integer[] arr1 = new Integer[]{4, 2, 6, 7, 1, -2, 0, -4, -3};
        List<Integer> list1 = Arrays.asList(arr1);
        Integer[] arr2 = new Integer[]{3, 2, 3, 7, 1, -2, 0, -4, -3};
        List<Integer> list2 = Arrays.asList(arr2);
        System.out.println(ans.threeSum(list1));
        System.out.println(ans.threeSum(list2));
    }
    public List<List<Integer>> threeSum(List<Integer> nums) {
        int n = nums.size();
        nums=nums.stream().sorted().collect(Collectors.toList());
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        // 枚举 a
        for (int first = 0; first < n; ++first) {
            // 需要和上一次枚举的数不相同
            if (first > 0 && nums.get(first) == nums.get(first - 1)) {
                continue;
            }
            // c 对应的指针初始指向数组的最右端
            int third = n - 1;
            int target = -nums.get(first);
            // 枚举 b
            for (int second = first + 1; second < n; ++second) {
                // 需要和上一次枚举的数不相同
                if (second > first + 1 && nums.get(second) == nums.get(second-1)) {
                    continue;
                }
                // 需要保证 b 的指针在 c 的指针的左侧
                while (second < third && nums.get(second) + nums.get(third) > target) {
                    --third;
                }
                // 如果指针重合，随着 b 后续的增加
                // 就不会有满足 a+b+c=0 并且 b<c 的 c 了，可以退出循环
                if (second == third) {
                    break;
                }
                if (nums.get(second) + nums.get(third) == target) {
                    List<Integer> list = new ArrayList<Integer>();
                    list.add(nums.get(first));
                    list.add(nums.get(second));
                    list.add(nums.get(third));
                    ans.add(list);
                }
            }
        }
        return ans;
    }
}
